<script setup>
import { ref, defineEmits } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { getExportTemplate } from '@/api/learning'
import FileSaver from 'file-saver'
import { useUserStore } from '@/stores/user'
// 实例化仓库
const userStore = useUserStore()
// 接收到原生的双向数据
defineProps({
  modelValue: {
    type: Boolean
  },
})
// 声明发出的事件
const emit = defineEmits(['update:modelValue', 'renderView'])
// 关闭弹层
const handleClose = () => {
  // 修改父组件的数据
  emit('update:modelValue', false)
}

// 下载导入模板
const getTemplate = async () => {
  const res = await getExportTemplate()
  FileSaver.saveAs(res.data, '学习路模板.xlsx')
}

// 导入成功的回调
const handleSuccess = () => {
  // 取消弹层
  handleClose()
  // 触发事件重新渲染
  emit('renderView')
}

// token
const headers = ref({ 'Authorization': userStore.userInfo.token })

</script>

<template>
  <!-- 绑定 -->
  <el-dialog width="530px" title="学习路" :model-value="modelValue" @close="handleClose">
    <el-upload class="upload-demo" ref="elUpload" drag :headers="headers" :on-success="handleSuccess"
      action="/prod-api/admin/learning/import" multiple>
      <div class="icon" style="margin-right: 32px">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      </div>
      <div class="btn" style="margin: 0 10px 0 0px;">
        <!-- 添加stop阻止事件冒泡 -->
        <el-button type="text" @click.stop="getTemplate" v-permissionDirective>下载导入模板</el-button>
      </div>
      <div class="el-upload__text" v-permissionDirective>
        将文件拖到此处或 <em>点击上传</em>
      </div>
    </el-upload>
    <el-row style="margin: 30px 0 0 450px;">
      <el-button size="small" type="primary" @click="handleClose">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<style scoped lang="scss">
.upload-demo {
  width: 500px;
  height: 200px;
}
</style>
